package cn.zcscloud.mall.controller;

import cn.zcscloud.mall.common.PageRequest;
import cn.zcscloud.mall.common.R;
import cn.zcscloud.mall.mbg.model.SmsCoupon;
import cn.zcscloud.mall.service.SmsCouponService;
import cn.zcscloud.mall.vo.SmsCouponParamVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/coupon")
public class SmsCouponController {
    @Autowired
    private SmsCouponService couponService;

    /**
     * 分页列表展示
     * @param name 模糊查询关键字
     * @param type 类型
     * @param pageSize 当前页显示记录
     * @param pageNum 页码
     * @return
     */
    @GetMapping("/list")
    public R list(String name,
                  Integer type,
                  @RequestParam( defaultValue = "5") Integer pageSize,
                  @RequestParam( defaultValue = "1") Integer pageNum){
        Page<SmsCoupon> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmsCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,SmsCoupon::getName,name)
                .eq(type != null,SmsCoupon::getType,type);
        Page<SmsCoupon> iPage = couponService.page(page, queryWrapper);
        return R.success(PageRequest.init(iPage));
    }

    /**
     * 添加优惠券
     * @param couponParam 优惠券信息
     * @return
     */
    @PostMapping("/create")
    public R create(@RequestBody SmsCouponParamVo couponParam){
        Boolean count = couponService.create(couponParam);
        if (count){
            return R.success("");
        }
        return R.error("添加失败",403);
    }

    @PostMapping("/update/{id}")
    public R update(@PathVariable Long id,@RequestBody SmsCouponParamVo couponParam){
        this.deleteById(id);
        return this.create(couponParam);
    }

    /**
     * 获取优惠券具体描述
     * @param id 主键检索
     * @return
     */
    @GetMapping("/{id}")
    public R getItem(@PathVariable Long id){
        SmsCouponParamVo couponParamVo = couponService.getItem(id);
        return R.success(couponParamVo);
    }

    @PostMapping("/delete/{id}")
    public R deleteById(@PathVariable Long id){
        Boolean b = couponService.deleteById(id);
        if (b){
            return R.success("");
        }
        return R.error("移除失败",403);
    }
}
